package com.zm.zyz.util;

import com.google.gson.Gson;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Utils {
    public  static void print(HttpServletResponse resp, Object object) throws IOException {
        Gson gson = new Gson();
        String json = gson.toJson(object);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(json);
    }

    //模板模式
    public static Object exec(java.util.function.Function<SqlSession,Object> handler){
        SqlSession sqlSession = null;
        Object ret = null;
        try {
            sqlSession = MyBatisHelper.getSession();
            //handler 业务代码实现
            ret = handler.apply(sqlSession);
            sqlSession.commit();
            return ret;
        } catch (RuntimeException e) {
            sqlSession.rollback();
            throw e;
        } finally {
            sqlSession.close();
        }
    }
}
